package com.mo.service.realm;


import com.mo.dao.SysMenuDao;
import com.mo.dao.SysUserDao;
import com.mo.pojo.SysUser;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;

import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;


public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    private SysMenuDao sysMenuDao;
@Autowired
private SysUserDao sysUserDao;
    /*
   认证信息
    */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken authenticationToken) throws AuthenticationException {

        //1.获取用户提交的认证用户信息
        UsernamePasswordToken upToken=
                (UsernamePasswordToken) authenticationToken;
        String uName=upToken.getUsername();
        //2.基于用户名查询从数据库用户信息
        SysUser user= sysUserDao.selectUserByuName(uName);
        //3.判断用户是否存在
        if(user==null)throw new UnknownAccountException();;//账户不存在

        //4.封装认证信息并返回
        return new SimpleAuthenticationInfo(user,//principal用户身份(基于业务设置)
                user.getUPwd(),//hashedCredentials 已加密的凭证(密码)
                this.getName());//realmName



    }




    /*
    授权信息
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(
            PrincipalCollection principalCollection) {
        //1.获取登录用户信息
        SysUser user= (SysUser) principalCollection.getPrimaryPrincipal();

        Set<String> stringPermissions=
                sysMenuDao.selectUserPermissions(user.getUCode());
        //3.封装数据并返回
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.setStringPermissions(stringPermissions);
        return info;

    }



}
